package com.ruoyi.web.controller.ueditor;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.druid.sql.visitor.functions.Substring;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.ServerConfig;

/**
 * 图片上传
 */

@RestController
@RequestMapping(value = "ueditor")
public class BaiduUeditorController {
	
	 @Autowired
	 private ServerConfig serverConfig;

    /**
     * 上传单张图片
     * @return 
     */
	@Anonymous
    @RequestMapping(value = "uploadimage", method = RequestMethod.POST)
    public AjaxResult upload(@RequestParam("upfile") MultipartFile file) throws IOException {
	//仅做演示，具体实现代码很简单，这里不作展示，这里会有一个iframe跨域的问题，别急，后面会给出解决方法
	/*String result = "{\"state\": \"SUCCESS\",\"original\": \"f59ace3303a2978faf3972e97397cdf.png\",\"size\": \"64079\",\"title\": \"1539934227542006306.png\",\"type\": \".png\",\"url\": \"1.jpg\"}";
	response.setContentType("text/html;charset=UTF-8");
	response.getWriter().write(result);*/
	try
    {
	    // 上传文件路径
	    String filePath = RuoYiConfig.getUploadPath();
	    // 上传并返回新文件名称
	    String fileName = FileUploadUtils.upload(filePath, file);
	    String url = fileName.substring(9);
	    AjaxResult ajax = AjaxResult.success();
	    ajax.put("state", "SUCCESS");
	    ajax.put("url", url);
	    return ajax;
    }
    catch (Exception e)
    {
        return AjaxResult.error(e.getMessage());
    }
}
     
    /**
     * 获取图片上传默认配置
     */

    @RequestMapping(value = "uploadimage", method = RequestMethod.GET)
    public void config(HttpServletRequest request,HttpServletResponse response) throws IOException  {
	//仅做演示，具体实现代码很简单，这里不作展示
	String result = "{\"imageInsertAlign\":\"none\",\"imageMaxSize\":2048000,\"imageAllowFiles\":[\".png\",\".jpg\",\".jpeg\",\".gif\",\".bmp\"],\"imagePathFormat\":\"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\"imageActionName\":\"uploadimage\",\"imageCompressEnable\":true,\"imageFieldName\":\"upfile\",\"imageCompressBorder\":1600,\"imageUrlPrefix\":\"/prod-api/profile/\"}";
	response.setContentType("text/html;charset=UTF-8");
	response.getWriter().write(result);
    }
 
}